<template>
  <div class="factory-customers-mine">
    <div class="factory-page-list">
      <div class="search-header">
        <el-input v-model="searchInput" size="small" placeholder="输入搜索关键字" @keyup.13.native="onSearch">
          <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="searchInput.length"></i>
          <el-button type="primary" slot="append" icon="el-icon-search" @click="onSearch"></el-button>
        </el-input>
        <el-tooltip effect="dark" content="新建分组" placement="top">
          <el-button type="primary" class="add-btn" @click="editGroup('add')">
            <icon-svg name="iconGroup"></icon-svg>
          </el-button>
        </el-tooltip>
      </div>
      <template v-if="groupList.length || loading">
        <el-collapse v-model="activeCollapse" accordion>
          <el-collapse-item v-for="(item, index) in groupList" :key="item.groupId" :name="item.groupId">
            <div slot="title" class="group-title">
              <i
                class="icon-toggle"
                :class="activeCollapse === item.groupId ? 'el-icon-caret-bottom' : 'el-icon-caret-right'"
              ></i>
              <el-tooltip effect="dark" :content="item.groupNm" placement="top-start">
                <span class="name">{{ item.groupNm }}</span>
              </el-tooltip>
              <el-popover placement="right-start" width="120" trigger="hover" popper-class="tag-group-handler">
                <ul>
                  <li @click="handleAdd(item)"><i class="el-icon-circle-plus-outline"></i>添加客群</li>
                  <li @click="handleImport(item)"><i class="el-icon-circle-plus-outline"></i>导入客群</li>
                  <template v-if="item.groupId">
                    <li @click="editGroup('edit', item)">
                      <icon-svg name="iconFacEdit" class="el-edit"></icon-svg>
                      编辑分组
                    </li>
                    <li @click="deleteGroup(item)">
                      <icon-svg name="iconDelete" class="el-delete"></icon-svg>
                      删除分组
                    </li>
                  </template>
                </ul>
                <i class="el-icon-more group-handler" slot="reference"></i>
              </el-popover>
            </div>
            <div class="factory-list">
              <template v-if="item.page.results.length">
                <ul class="list-wrap">
                  <li
                    class="list-item"
                    :class="{ 'is-active': cust.tagId === selectTag.tagId }"
                    v-for="cust in item.page.results"
                    :key="cust.tagId"
                    @click="selectItem(cust)"
                  >
                    <icon-svg name="iconResTeam"></icon-svg>
                    <span class="list-name elli">{{ cust.derivedName }}</span>
                    <el-tooltip effect="dark" placement="top" :enterable="false">
                      <span slot="content">
                        创建人：{{ $name(cust, 'creatorNname', 'creatorUser') }}
                        <br />
                        <br />
                        创建时间: {{ cust.createTm }}
                      </span>
                      <icon-svg name="iconPreview"></icon-svg>
                    </el-tooltip>
                  </li>
                </ul>
                <el-pagination
                  style="text-align: right"
                  :current-page="item.page.params.currentPageNum"
                  :page-size="item.page.params.pageSize"
                  background
                  layout="total, prev, pager, next"
                  :total="item.page.totalSize"
                  :pager-count="5"
                  small
                  @current-change="handleCurrentChange($event, index)"
                >
                </el-pagination>
              </template>
              <div class="no-record" v-else>暂无客群</div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </template>
      <div class="no-record" v-else>暂无分组</div>
    </div>
    <tag-group ref="tagGroup" @callback="getResults"></tag-group>
    <factory-content-container ref="factoryContainer" type="users" @callback="refresh"></factory-content-container>
  </div>
</template>

<script>
import FactoryContentContainer from './factory-content-container'
import $factory from './api'
export default {
  name: 'FactoryGroupMine',
  components: { FactoryContentContainer },
  data() {
    return {
      loading: false,
      searchInput: '',
      activeCollapse: -1,
      groupList: [],
      selectTag: {}
    }
  },
  watch: {
    activeCollapse() {
      this.getTags()
    }
  },
  methods: {
    init() {
      this.getResults()
    },
    getResults() {
      // 获取我的所有分组
      this.$nextTick(() => {
        this.loading = true
        this.$refs.factoryContainer.setLoading(true)
        $factory.getAllGroup().then(({ data }) => {
          if (data && data.code === '0') {
            this.groupList = [{ groupId: 0, groupNm: '默认分组' }, ...data.data]
            this.groupList.forEach(item => {
              item.page = {
                results: [],
                params: {
                  ascs: [],
                  descs: [],
                  currentPageNum: 1,
                  pageSize: 10,
                  queryParams: {
                    groupId: item.groupId
                  },
                  descPriority: false
                },
                totalSize: 0
              }
            })
            if (!this.selectTag.tagId) this.activeCollapse = 0
            else {
              this.getTags()
              this.$refs.factoryContainer.setLoading(false)
            }
          } else {
            this.$message.error(data.data || data.msg)
            this.$refs.factoryContainer.setLoading(false)
          }
          this.loading = false
        })
      })
    },
    getTags() {
      const group = this.groupList.find(item => item.groupId === this.activeCollapse)
      const index = this.groupList.findIndex(item => item.groupId === this.activeCollapse)
      if (group) {
        this.$refs.factoryContainer.setLoading(true)
        let params = group.page.params
        if (this.searchInput) params.queryParams.derivedName = this.searchInput
        this.$ajax({
          url: this.$ajax.setUrl('ast/astTagDerivedGroup/getDerivesPage'),
          method: 'get',
          params: this.$ajax.setParams(group.page.params)
        }).then(({ data }) => {
          if (data && data.code === '0') {
            this.groupList[index].page.results = data.data.records
            this.groupList[index].page.totalSize = data.data.totalSize
            let maxPageNum = Math.ceil(data.data.totalSize / group.page.params.pageSize) || 1
            if (group.page.params.currentPageNum > maxPageNum) {
              group.page.params.currentPageNum = maxPageNum
              this.getTags()
            }
            this.$forceUpdate()
            if (data.data.records.length) {
              if (!this.selectTag.tagId) this.selectItem(data.data.records[0])
              else {
                const dataItem = this.groupList[index].page.results.find(item => item.tagId === this.selectTag.tagId)
                this.selectItem(dataItem ? dataItem : data.data.records[0])
              }
            } else {
              this.$refs.factoryContainer.setLoading(false)
            }
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      }
    },
    onSearch() {
      this.activeCollapse = ''
      this.selectTag = {}
      if (!this.searchInput) {
        this.getResults()
      } else {
        this.searchMyDerived(this.searchInput)
      }
    },
    clearSearch() {
      this.searchInput = ''
      this.onSearch()
    },
    selectItem(item) {
      this.selectTag = item
      this.$refs.factoryContainer.update(item)
    },
    handleCurrentChange(num, index) {
      this.groupList[index].page.params.currentPageNum = num
      this.getTags()
    },
    editGroup(type = 'add', item = {}) {
      this.$refs.tagGroup.showDialog({ type, groupId: item.groupId, groupNm: item.groupNm, groupType: 1 })
    },
    deleteGroup(item) {
      // 删除分组
      this.$confirm(`是否确认删除分组【${item.groupNm}】?`).then(() => {
        let messageBox = document.getElementsByClassName('el-message-box__wrapper')
        messageBox[0].focus() // 防止按空格键重复确定
        $factory.deleteDerivedGroup({ id: item.groupId }).then(({ data }) => {
          if (data && data.code === '0') {
            this.$message.success(data.msg)
            this.getResults()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      })
    },
    searchMyDerived(text = '') {
      // 搜索客群
      $factory.searchMyDerived({ tagNm: text }).then(({ data }) => {
        if (data && data.code === '0') {
          this.groupList = data.data
          this.groupList.forEach(item => {
            item.page = {
              results: [],
              params: {
                ascs: [],
                descs: [],
                currentPageNum: 1,
                pageSize: 10,
                queryParams: {
                  groupId: item.groupId
                },
                descPriority: false
              },
              totalSize: 0
            }
          })
          if (!this.selectTag.tagId && this.groupList.length) this.activeCollapse = this.groupList[0].groupId
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    refresh() {
      // this.selectTag = {}
      this.getTags()
    },
    handleAdd(item) {
      this.$blank('factory-config', { query: { groupId: item.groupId } })
    },
    handleImport(item) {
      this.$blank('factory-import', { query: { groupId: item.groupId } })
    }
  },
  created() {
    this.getResults()
  }
}
</script>

<style lang="scss">
.factory-customers-mine {
  height: 100%;
  .search-header {
    margin-bottom: 10px;
    .el-input__suffix {
      top: 5px;
    }
    .el-input__suffix-inner {
      font-size: 18px;
      color: #4d82e9;
    }
  }
  .add-btn {
    height: 33px;
    margin-left: 10px;
    padding: 0 15px;
    color: #455fbc;
    background-color: #e4eafe;
    border-color: #e4eafe;
    svg {
      width: 18px;
      height: 18px;
    }
  }
  .el-collapse-item__header {
    font-size: 16px;
    height: 45px;
    padding: 0 10px;
    line-height: 45px;
    &:hover {
      background-color: #efefef;
    }
  }
  .el-collapse-item__arrow {
    display: none;
  }
  .icon-toggle {
    font-size: 18px;
    color: #4d82e9;
  }
  .el-collapse-item__content {
    padding-bottom: 0;
  }
  .no-record {
    text-align: center;
  }
  .factory-list {
    padding: 0 25px;
    .list-item {
      padding: 5px;
      svg {
        width: 15px;
        height: 15px;
      }
    }
  }
  .group-title {
    width: 100%;
    position: relative;
    padding-right: 20px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    .name {
      margin-left: 10px;
    }
  }
  .group-handler {
    color: #4d82e9;
    position: absolute;
    top: 15px;
    right: 0;
  }
}
</style>
